import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '@/pinia/modules/user';
import { useRouterStore } from '@/pinia/modules/router';
import Nprogress from 'nprogress';

const routes = [{
  path: '/',
  redirect: '/login'
}, {
  path: '/login',
  name: 'login',
  meta: {
    title: '会员登录',
  },
  component: () => import('@/view/login.vue')
}, {
  path: '/register',
  name: 'register',
  meta: {
    title: '会员注册',
  },
  component: () => import('@/view/register.vue')
}];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_BASE_STATIC_PATH),
  routes
});

let isInitRouter = false;
const whiteList = ['login', 'register'];

const initRouter = async(userStore) => {
  // 初始化用户信息
  await userStore.initUserInfo();

  // 初始化路由信息
  const routerStore = useRouterStore();
  await routerStore.initRouter(router);
};

const handleKeepAlive = async(to) => {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1]
        if (element.name === 'layout') {
          to.matched.splice(i, 1)
          await handleKeepAlive(to)
        }
        // 如果没有按需加载完成则等待加载
        if (typeof element.components.default === 'function') {
          await element.components.default()
          await handleKeepAlive(to)
        }
      }
    }
  }
};

router.beforeEach(async(to, from) => {
  Nprogress.start();
  const userStore = useUserStore();
  to.meta.matched = [...to.matched];
  await handleKeepAlive(to);
  const token = userStore.getToken();
  // 在白名单中的判断情况
  if (whiteList.indexOf(to.name) > -1) {
    if (token) {
      if (!isInitRouter && whiteList.indexOf(from.name) < 0) {
        isInitRouter = true;
        await initRouter(userStore);
      }
      return { name: 'home' };
    } else {
      return true;
    }
  } else {
    // 不在白名单中并且已经登录的时候
    if (token) {
      // 添加flag防止多次获取动态路由和栈溢出
      if (!isInitRouter && whiteList.indexOf(from.name) < 0) {
        isInitRouter = true;
        await initRouter(userStore);
        if (userStore.getToken()) {
          return { ...to, replace: true };
        } else {
          return { name: 'login' };
        }
      } else {
        if (to.matched.length) {
          return true;
        } else {
          return { name: 'notfound' };
        }
      }
    } else {
      // 不在白名单中并且未登录的时候
      return { name: 'login' };
    }
  }
});

router.afterEach(() => {
  // 路由加载完成后关闭进度条
  Nprogress.done();
});

router.onError(() => {
  // 路由发生错误后销毁进度条
  Nprogress.remove();
});

export default router;
